package com.lsj.core.advice;


import com.lsj.core.exception.CustomerException;
import com.lsj.core.response.CommonResult;
import com.lsj.core.response.ResponseType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ValidationException;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    /*处理能在系统预知情况下的异常问题*/
    @ExceptionHandler(value = CustomerException.class)
    public CommonResult handlerCustomerException(CustomerException e){
        return CommonResult.error(e);
    }

    /*在进入controller调用@validate校验入参，若不符合，则抛出该异常*/
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handleValidateException(MethodArgumentNotValidException e){
        String errMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        return CommonResult.error(errMsg);
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public CommonResult handleValidationException(ValidationException e) {
        CommonResult response = CommonResult.error(e.getMessage());
        return response;
    }

    /**
     * ConstraintViolationException
     */
//    @ExceptionHandler(ConstraintViolationException.class)
//    @ResponseBody
//    public CommonResult handleConstraintViolationException(ConstraintViolationException e) {
//        return CommonResult.error(e.getMessage());
//    }

    /*处理系统未知异常*/
    @ExceptionHandler(value = Exception.class)
    public CommonResult handleUnknowException(Exception e) throws Exception{
        /*security方法级别的权限校验PreAuthorize和PostAuthorize，抛出的异常不会被accessDeinedHandler处理
        * 原因在于这个方法级别的aop，可以认为此时已经*/
        if(e instanceof AccessDeniedException){

            return CommonResult.error(new CustomerException(ResponseType.forbid,"权限不足，不允许访问！"));
        }
        return CommonResult.error(ResponseType.system_error, e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResult urlNotFoundException(Exception e){
        return CommonResult.error("当前请求路径不存在，请检查路径是否正确");
    }


}
